<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseController;
use App\Models\User;

use App\Rules\Phone;
use Illuminate\Http\Request;
use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Auth;
use Mail;
use DB;
use PhpParser\Node\Scalar\String_;


class UserController extends BaseController
{

    //用户列表展示
    public function index(){
        //带软删除查询
        $datas = User::withTrashed()->orderby('id','asc')->paginate($this->pageSize);
        return view('admin.user.index',compact('datas'));
    }

    //显示添加用户页面
    public function create(){
        return view('admin.user.create');
    }

    //添加用户处理
    public function store(Request $request){

        //表单验证
        $this->validate($request, [
            'username' => 'required|unique:users',
            'truename' => 'required',
            'password' => 'required|confirmed',
            'email'    => 'required|email',
            'phone'    => ['required',new Phone()],
        ]);

        $params = $request->except(['_token','_method','password_confirmation']);
        $params['password'] = bcrypt($params['password']);
        $user = User::create($params);

        //发送邮件给用户
        $password = $request->get('password');
        Mail::send('mail.addUser',compact('user','password' ), function (Message $message) use($user){
            //指定发送人
            $message->to($user->email);
            $message->subject('开通账号通知');
        });

        return redirect(route('admin.user.index'))->with(['success'=>'添加用户成功']);
    }

    //软删除用户
    public function del(Request $request, $id){
       $user = User::find($id)->delete();
        return ["status"=>1, "msg"=>"删除成功"];
    }

    //恢复用户
    public function recover(Request $request, $id){
        User::withTrashed()->find($id)->restore();
        return redirect(route('admin.user.index'))->with("success","恢复用户成功");
    }

    //删除选中的所有用户
    public function deleteAll(Request $request){
        $ids = $request->get('ids');
        User::destroy($ids);
        return ["status"=>1, "msg"=>"删除成功"];
    }

    //显示修改信息页 (管理员修改用户信息)
    public function showUpdate(int $id){
        $user = DB::table('users')->where('id',$id)->first();
        return view('admin.user.showUpdate',compact('user'));
    }
    //处理修改 (管理员修改用户信息)
    public function update(Request $request, int $id){
        $user = User::find($id);
        $data = $request->only([
            'truename',
            'password',
            'gender',
            'phone',
            'email'
        ]);
        //去除空的内容
        foreach ($data as $k=>$val){
            if ($val == ''){
                unset($data[$k]);
            }
        }
        //加密不要放在循环里面, 会被多次加密导致密码校验不通过
        if (isset($data['password'])){
            $data['password'] = bcrypt($data['password']);
        }

        $user->update($data);
        return redirect(route('admin.user.index'))->with(['success'=>"修改成功"]);
    }

    //显示修改页  (修改个人信息)
    public function detail(){
        return view('admin.user.detail');
    }
    //修改用户信息 (修改个人信息)
    public function updateMyself(Request $request){
        //表单验证
        $this->validate($request, [
            'truename' => 'required',
            'password' => 'required',
            'new_password' => 'confirmed',
            'email'    => 'required|email',
            'phone'    => ['required',new Phone()],
            'gender'   => 'required'
        ],[
            'new_password.confirmed' => '两次输入的新密码不一致',
        ]);

        //校验原始密码
        $check = $this->checkpwd($request);
        if ($check['status'] == 0){
           return back()->withErrors(['密码错误, 请重新输入']);
        }

        $data = $request->only([
            'truename',
            'new_password',
            'email',
            'phone',
            'gender'
        ]);
        if (!empty($data['new_password'])){
            $data['password'] = bcrypt($data['new_password']);
        }
        unset($data['new_password']);
        DB::table('users')->where('id',Auth::user()->id)->update($data);
        return back()->with(['success'=>'修改成功']);
    }

    //ajax检查原密码是否正确
    public function checkpwd(Request $request){
        $password = $request->get('password');
        $user = Auth::user();
        $data = [
            "password" => $password,
            "username" => $user->username
        ];
        if (Auth::attempt($data)){
            return ['status'=>1,"msg"=>"密码正确"];
        }
        return ['status'=>0,"msg"=>"密码错误"];
    }


}
